package cn.fan.whale.service.impl;

import cn.fan.whale.entity.po.RoleEntity;
import cn.fan.whale.entity.po.RoleSourceMidEntity;
import cn.fan.whale.entity.vo.DistributeRequest;
import cn.fan.whale.mapper.RoleSourceMidMapper;
import cn.fan.whale.service.RoleService;
import cn.fan.whale.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;

    private final RoleSourceMidMapper roleSourceMidMapper;

    public RoleServiceImpl(RoleMapper roleMapper, RoleSourceMidMapper roleSourceMidMapper) {
        this.roleMapper = roleMapper;
        this.roleSourceMidMapper = roleSourceMidMapper;
    }

    @Override
    public PageInfo<RoleEntity> findByPage(Integer pageNum, Integer pageSize, RoleEntity roleEntity) {
        PageHelper.startPage(pageNum, pageSize);
        List<RoleEntity> list = roleMapper.selectBySelective(roleEntity);
        return new PageInfo<>(list);
    }

    @Override
    public List<RoleEntity> findAll() {
        RoleEntity param = new RoleEntity();
        return roleMapper.selectBySelective(param);
    }

    @Override
    public void save(RoleEntity roleEntity) {
        Date nowDate = new Date();
        roleEntity.setCtime(nowDate);
        roleEntity.setMtime(nowDate);
        roleEntity.setAvailable(1);
        roleMapper.insert(roleEntity);
    }

    @Override
    public void distribute(DistributeRequest distributeRequest) {
        roleSourceMidMapper.deleteByRoleId(distributeRequest.getRoleId());
        Integer roleId = distributeRequest.getRoleId();
        List<Integer> sourceIdList = distributeRequest.getSourceIdList();
        List<RoleSourceMidEntity> roleSourceMidEntityList = new ArrayList<>();
        Date nowDate = new Date();
        for (Integer sourceId : sourceIdList) {
            RoleSourceMidEntity roleSourceMidEntity = new RoleSourceMidEntity();
            roleSourceMidEntity.setRoleId(roleId);
            roleSourceMidEntity.setSourceId(sourceId);
            roleSourceMidEntity.setCtime(nowDate);
            roleSourceMidEntity.setMtime(nowDate);
            roleSourceMidEntityList.add(roleSourceMidEntity);
        }
        if (!roleSourceMidEntityList.isEmpty()) {
            roleSourceMidMapper.insertBatch(roleSourceMidEntityList);
        }
    }

    @Override
    public void update(RoleEntity roleEntity) {
        Date nowDate = new Date();
        roleEntity.setMtime(nowDate);
        roleMapper.updateByPrimaryKeySelective(roleEntity);
    }

    @Override
    public void delete(Integer roleId) {
        roleMapper.deleteByPrimaryKey(roleId);
        roleSourceMidMapper.deleteByRoleId(roleId);
    }
}
